const express = require('express');
const async = require('async');
const pool = require('../pool');
const router = express.Router();

// 获取首页商品列表
router.get('/list',(req,res)=>{
  let callback = req.query.callback;
  let output = {};
  let progress = 0;
  let sql = 'select img,href,title,price from igou_index_products where section=';
  pool.getConnection((err,conn)=>{
    for(let i=1;i<=4;i++){
      conn.query(sql+i,(err,result)=>{
        if(err) throw err;
        output['section'+i] = result;
        if(++progress===4){
          output = JSON.stringify(output);
          res.send(callback+'('+output+')');
        }
      });
    }
    conn.release();
  })
});

//获取首页推荐列表
router.get('/recommend',(req,res)=>{
  let callback = req.query.callback;
  let page = req.query.page || 1;
  let pageSize = req.query.pageSize || 8;
  let pageCount = req.query.pageCount;
  let output = {};
  let progress = 0;
  
  pool.getConnection((err,conn)=>{
    let sql = `select product_id as pid,title,price,sold_count as count,(select md from igou_product_pic where product_id=pid limit 1) as img from igou_product limit ${(page-1)*pageSize},${pageSize}`;
    conn.query(sql,(err,result)=>{
      if(err) throw err;
      output.data = result;
      progress += 50;
      if(progress === 100){
        output = JSON.stringify(output);
        res.send(callback+'('+output+')');
      }
    });
    if(pageCount=='0'){
      sql = 'select count(product_id) as total from igou_product';
      conn.query(sql,(err,result)=>{
        if(err) throw err;
        console.log('查询商品总数...')
        output.pageCount = Math.ceil(result[0].total / pageSize);
        progress += 50;
        if(progress === 100){
          output = JSON.stringify(output);
          res.send(callback+'('+output+')');
        }
      });
    }else {
      output.pageCount =pageCount;
      progress += 50;
    }
    conn.release();
  })
})

// 获取商品详情
router.get('/details',(req,res)=>{
  let pid = req.query.pid;
  let output = {};
  let options = [
    {
      key: 'carousel',
      sql: 'select md from igou_product_pic where product_id=?'
    },
    {
      key: 'info',
      sql: 'select family_id,title,subtitle,price,promise,os,memory,resolution,video_card,cpu,video_memory,category,disk,sold_count from igou_product where product_id=?'
    },
    {
      key: 'list',
      sql: 'select product_id as pid,spec,price,sold_count from igou_product where family_id=(select family_id from igou_product where product_id=?)'
    }
  ];
  
  pool.getConnection((err,conn)=>{
    async.each(options,(item,callback)=>{
      conn.query(item.sql,[pid],(err,result)=>{
        output[item.key] = result;
        callback(err);
      });
    },err=>{
      if(err) console.error(err);
      res.json(output);
      conn.release();
    })
  })
})

module.exports = router;